// #define print(...)

class Solution {
public:
    int numSubarraysWithSum(vector<int>& nums, int goal) {
        auto left = nums.begin(), mid = left;
        int sum = 0, sumFromLeft = 0, sumFromMid = 0, ans = 0;
        for(auto right=left; right != nums.end(); right++){
            sumFromLeft += *right;
            while(left <= right && goal < sumFromLeft)
                sumFromLeft -= *left++;
            sumFromMid += *right;
            while(mid <= right  && goal <=sumFromMid)
                sumFromMid -= *mid++;
            ans += mid - left;
        }
        return ans;
    }
};
